package org.raymond.iworks.study.orders.common;

import lombok.Getter;
import lombok.Setter;
import org.raymond.iworks.study.orders.entity.TInventoriesSeckillBook;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedTransferQueue;

@Getter
public class GlobalCache {
    private Map<Long, List<String>> segmentProductLockMap;
    private Map<Long, Integer> rotateCountMap;
    private Map<Long, Integer> maxMap;
    private LinkedTransferQueue<TInventoriesSeckillBook> seckillQueue;
    private GlobalCache(){}

    private void setSegmentProductLockMap(Map<Long, List<String>> segmentProductLockMap){
        this.segmentProductLockMap = segmentProductLockMap;
    }
    private void setRotateCountMap(Map<Long, Integer> rotateCountMap){
        this.rotateCountMap = rotateCountMap;
    }
    private void setMaxMap(Map<Long, Integer> maxMap){
        this.maxMap = maxMap;
    }
    public void register(TInventoriesSeckillBook seckillBook){
        if(seckillQueue==null){
            seckillQueue = new LinkedTransferQueue<>();
        }
        seckillQueue.add(seckillBook);
    }

    public boolean segmentProductLocksNotEmpty(Long productId){
        boolean notEmpty = false;
        if(segmentProductLockMap!=null){
            List<String> segmentProductLockList = segmentProductLockMap.get(productId);
            if(segmentProductLockList!=null){
                notEmpty = segmentProductLockList.size()>0;
            }
        }
        if(rotateCountMap!=null){
            Integer atomicSegmentIdx = rotateCountMap.get(productId);
            notEmpty = notEmpty && atomicSegmentIdx!=null;
        }
        return notEmpty;
    }
    private static class InstanceHolder {
        private static final GlobalCache INSTANCE = new GlobalCache();
    }

    public static void injectSegmentlockMap(Map<Long, List<String>> segmentLockMap){
        if(GlobalCache.InstanceHolder.INSTANCE.getSegmentProductLockMap()==null && segmentLockMap!=null && !segmentLockMap.isEmpty()){
            GlobalCache.InstanceHolder.INSTANCE.setSegmentProductLockMap(segmentLockMap);
        }
    }
    public static void injectRotateCountMap(Map<Long, Integer> rotateCountMap){
        if(GlobalCache.InstanceHolder.INSTANCE.getRotateCountMap()==null && rotateCountMap!=null && !rotateCountMap.isEmpty()){
            GlobalCache.InstanceHolder.INSTANCE.setRotateCountMap(rotateCountMap);
        }
    }
    public static void injectMaxMap(Map<Long, Integer> maxMap){
        if(GlobalCache.InstanceHolder.INSTANCE.getMaxMap()==null && maxMap!=null && !maxMap.isEmpty()){
            GlobalCache.InstanceHolder.INSTANCE.setMaxMap(maxMap);
        }
    }

    public static GlobalCache instance(){
        return GlobalCache.InstanceHolder.INSTANCE;
    }
}
